<?php


namespace app\controller\api;


use app\BaseController;

use app\common\exception\ApiException;
use app\common\RedisKey;
use app\facade\RedisLocationFacade;
use app\model\cart\VerifyCartComplaintModel;
use app\model\cart\VerifyCartModel;
use app\model\coach\UserCoachModel;
use app\model\config\RegionModel;
use app\model\goods\OrderModel;
use app\model\partner\EscortMenuReserveOrderModel;
use app\model\school\SchoolBaseModel;
use app\model\school\SchoolCourseModel;
use app\model\school\SchoolModel;
use app\model\school\SchoolOrderModel;
use app\model\user\UserCouponModel;
use app\model\user\UserModel;
use app\service\config\ConfigService;
use app\service\order\SchoolOrderService;
use app\service\user\UserCouponService;
use app\service\utils\WeiXinPayService;
use GuzzleHttp\Exception\GuzzleException;
use think\db\Query;
use think\facade\Db;
use think\facade\Log;

class StudyCartController extends BaseController
{
    /**
     * 开通城市列表
     * @return \think\response\Json
     */
    public function getOpenCityList()
    {
        try {
            $list = SchoolBaseModel::order('sort', 'desc')->select();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 驾校列表
     * @return \think\response\Json
     */
    public function getSchoolList()
    {
        try {
            $search = $this->request->param('search', '', 'trim');
            $cityId = $this->request->param('city_id', 0, 'int');
            $sort = $this->request->param('sort', 0, 'int');

            $lng = $this->request->param('lng', 0, 'trim');
            $lat = $this->request->param('lat', 0, 'trim');

            $where = [];
            if ($cityId) {
                $where [] = ['city_id', '=', $cityId];
            }
            if ($search != '') {
                $where [] = ['name', 'like', "%$search%"];
            }
            $order = ['is_recommend' => 'desc'];
            if ($sort == 2) {
                $order = ['num' => 'desc'];
            }
            if ($sort == 3) {
                $order = ['num' => 'asc'];
            }
            $locationArr = RedisLocationFacade::getMembersByDistance(RedisKey::ALL_SCHOOL_LIST, $lng, $lat, 5000);
            if (!$locationArr) {
                $where[] = ['id', '=', 0];
                $schoolIdStr = '0';
                $distanceArr = [];
            } else {
                $locationArr = RedisLocationFacade::formatLocation($locationArr);
                $schoolIdArr = $locationArr['key'];
                $distanceArr = $locationArr['value'];
                $schoolIdStr = implode(',', $schoolIdArr);
                $where [] = ['id', 'in', $schoolIdArr];
            }


            $list = SchoolModel::with(['schoolBase', 'region'])
                ->field('id,img,intro,name,city_id,num,is_recommend,recommend_reason')
                ->where($where)
                ->when($sort == 1, function (Query $query) use ($schoolIdStr) {
                    $query->orderRaw("field(id,$schoolIdStr)");
                }, function (Query $query) use ($order) {
                    $query->order($order);
                })
                ->paginate(['list_row' => $this->limit, 'page' => $this->page])
                ->toArray();
            foreach ($list['data'] as $key => &$value) {
                $value['distance'] = number_format($distanceArr[$value['id']], 1);
                $value['course_list'] = SchoolCourseModel::where('school_id', $value['id'])
                    ->field('price,name')
                    ->order('price', 'asc')
                    ->limit(2)
                    ->select();
            }
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 驾校详情
     * @return \think\response\Json
     */
    public function getSchoolDetail()
    {
        try {
            $schoolId = $this->request->param('school_id', 0, 'int');
            if (!$schoolId) {
                throw new ApiException('缺少参数');
            }
            $lng = $this->request->param('lng', 0, 'trim');
            $lat = $this->request->param('lat', 0, 'trim');
            $info = SchoolModel::with(['schoolBase', 'region'])->find($schoolId);
            $info['tel'] = explode(',', $info['tel']);
            $info['distance'] = getDistance($lat, $lng, $info['lat'], $info['lng']);
            $typeList = SchoolCourseModel::where('school_id', $schoolId)->field('id,type')->group('type')->select();
            $info['type_list'] = $typeList;
            return $this->success($info);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 驾校课程
     * @return \think\response\Json
     */
    public function getCourseList()
    {
        try {
            $schoolId = $this->request->param('school_id', 0, 'int');
            $type = $this->request->param('type', '', 'trim');
            $list = SchoolCourseModel::where('school_id', $schoolId)->where('type', $type)->select();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 课程详情
     * @return \think\response\Json
     */
    public function getCourseDetail()
    {
        try {
            $courseId = $this->request->param('course_id', 0, 'int');
            $lng = $this->request->param('lng', 0, 'trim');
            $lat = $this->request->param('lat', 0, 'trim');

            $info = SchoolCourseModel::with(['school'])->find($courseId);
            if (!$info) {
                throw new ApiException('课程不存在');
            }
            $schoolId = $info['school_id'];
            $school = SchoolModel::find($schoolId);
            $info['address'] = $school['address'];
            $info['city'] = $school['city_name'];
            $info['tel'] = $school['tel'];

            $distance = getDistance($lat, $lng, $school['lat'], $school['lng']);
            $info['distance'] = $distance;

            return $this->success($info);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 学车订单
     * @return \think\response\Json
     */
    public function createStudyOrder()
    {
        try {
            $userId = $this->request->middleware('userId');
            $name = $this->request->param('name', '', 'trim');
            $mobile = $this->request->param('mobile', '', 'trim');
            $remark = $this->request->param('remark', '', 'trim');
            $courseId = $this->request->param('course_id', 0);

            $info = SchoolCourseModel::find($courseId);
            if (!$info) {
                throw new ApiException('信息不存在');
            }

            $coachId = UserCoachModel::where('school_id', $info['school_id'])
                ->where('is_team_leader', 1)
                ->value('id');
            if (!$coachId) {
                $coachId = UserCoachModel::where('school_id', $info['school_id'])
                    ->value('id');
            }

            $orderAmount = $info['price'];
            $orderSn = createOrderSn('school_order', 'order_sn', 'XC');

            $coachAmount = $orderAmount;
            $ratio = ConfigService::getConfigValue('platform_ratio', 0);
            if ($ratio) {
                $coachAmount = bcmul($orderAmount, (100 - $ratio) / 100, 2);
            }

            $schoolInfo = SchoolModel::find($info['school_id']);

            $orderModel = new OrderModel();
            $orderModel->order_sn = $orderSn;
            $orderModel->order_type = 2;
            $orderModel->user_id = $userId;
            $orderModel->city_id = $schoolInfo['city_id'];
            $orderModel->mobile = $mobile;
            $orderModel->save();

            $schoolOrderModel = new SchoolOrderModel();
            $schoolOrderModel->user_id = $userId;
            $schoolOrderModel->school_id = $info['school_id'];
            $schoolOrderModel->city_id = $schoolInfo['city_id'];
            $schoolOrderModel->type = $info['type'];
            $schoolOrderModel->course_id = $courseId;
            $schoolOrderModel->accept_uid = $coachId;
            $schoolOrderModel->coach_id = $coachId;
            $schoolOrderModel->order_sn = $orderSn;
            $schoolOrderModel->amount = $orderAmount;
            $schoolOrderModel->coach_amount = $coachAmount;
            $schoolOrderModel->username = $name;
            $schoolOrderModel->mobile = $mobile;
            $schoolOrderModel->remark = $remark;
            $schoolOrderModel->course_name = $info['name'];
            $schoolOrderModel->save();

            // 驾校报名人数

            $schoolInfo = SchoolModel::find($info['school_id']);
            $schoolInfo->num = Db::raw('num+1');
            $schoolInfo->save();
            return $this->success(['order_sn' => $orderSn, 'amount' => $orderAmount]);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     *订单可用优惠券
     * @return \think\response\Json
     */
    public function getPartnerDriveOrderCouponList()
    {
        try {
            $userId = $this->request->middleware('userId');
            $orderSn = $this->request->param('order_sn', '', 'trim');

            $orderInfo = SchoolOrderModel::where('order_sn', $orderSn)->find();
            if (!$orderInfo) {
                throw new ApiException('订单不存在');
            }
            if ($orderInfo['user_id'] != $userId) {
                throw new ApiException('非法请求');
            }
            $userCouponService = new UserCouponService();
            $list = $userCouponService->getOrderCouponList($userId, $orderInfo['amount'], 1);
            return $this->success(['total' => count($list), 'list' => $list]);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 订单支付
     * @return \think\response\Json
     */
    public function payPartnerDriveOrder()
    {
        try {
            $userId = $this->request->middleware('userId');
            $orderSn = $this->request->param('order_sn', '', 'trim');
            $userCouponId = $this->request->param('user_coupon_id', 0, 'int');
            $payType = $this->request->param('pay_type', 0, 'int');
            if ($payType == 2) {
                throw new ApiException('暂不支持该支付方式');
            }
            if (!$orderSn) {
                throw new ApiException('订单号错误');
            }
            $orderInfo = SchoolOrderModel::where('order_sn', $orderSn)->find();
            if (!$orderInfo) {
                throw new ApiException('订单不存在');
            }
            if ($orderInfo['user_id'] != $userId) {
                throw new ApiException('非法请求');
            }
            if ($orderInfo['status'] !== 1) {
                throw new ApiException('订单状态错误');
            }
            $userInfo = UserModel::find($orderInfo['user_id']);
            if (!$userInfo) {
                throw new ApiException('用户不存在');
            }
            $openID = $userInfo['openid'];
            if (!$openID) {
                throw new ApiException('用户未授权');
            }

            $orderAmount = $orderInfo['amount'];
            $couponAmount = 0;
            if ($userCouponId) {
                $couponAmount = UserCouponModel::where('id', $userCouponId)->where('user_id', $userId)->value('amount', 0);
            }
            $payAmount = $orderAmount - $couponAmount;
            if ($payAmount <= 0) {
                throw new ApiException('支付金额错误');
            }
            $orderInfo->user_coupon_id = $userCouponId;
            $orderInfo->pay_amount = $payAmount;
            $orderInfo->pay_type = $payType;
            $orderInfo->save();

            $service = new WeiXinPayService();
            $notifyUrl = $this->request->domain() . '/api/notify/studyCardNotify';
            $result = $service->pay($orderSn, $orderInfo['pay_amount'], $openID, $notifyUrl, '学车订单支付');
            return $this->success($result);
        } catch (\Exception $exception) {
            return $this->error($exception);
        } catch (GuzzleException $e) {
            return $this->error($e);
        }
    }

    /**
     * 我的学车订单
     * @return \think\response\Json
     */
    public function getMyStudyOrder()
    {
        try {
            $userId = $this->request->middleware('userId');
            $list = SchoolOrderModel::with(['school', 'course', 'base', 'city'])
                ->where('user_id', $userId)
                ->where('status', '>', 0)
                ->order('id', 'desc')
                ->select();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 上传券码
     * @return \think\response\Json
     */
    public function uploadCode()
    {
        try {
            $orderId = $this->request->param('order_id', 0, 'int');
            $code = $this->request->param('code', '', 'trim');
            $img = $this->request->param('img', '', 'trim');
            if (!$code && !$img) {
                throw new ApiException('请上传券码或图片');
            }
            $schoolOrderModel = SchoolOrderModel::find($orderId);
            if (!$schoolOrderModel) {
                throw new ApiException('订单不存在');
            }
            $schoolOrderModel->coupon_code = $code;
            $schoolOrderModel->coupon_code_img = $img;
            $schoolOrderModel->status = SchoolOrderModel::ORDER_CHECK_COUPON;
            $schoolOrderModel->save();
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 完成订单
     * @return \think\response\Json
     */
    public function completeOrder()
    {
        try {
            $id = $this->request->param('id', 0, 'int');
            if ($id <= 0) {
                throw new ApiException('参数错误');
            }
            $schoolOrderService = new SchoolOrderService();
            $schoolOrderService->completeOrderService($id);
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 订单投诉
     */
    public function complaintOrder()
    {
        try {
            $userId = $this->request->middleware('userId');
            $orderId = $this->request->param('order_id', 0, 'int');
            $img = $this->request->param('img', '', 'trim');
            $content = $this->request->param('content', '', 'trim');

            $orderInfo = VerifyCartModel::where('id', $orderId)->where('user_id', $userId)->find();
            if (!$orderInfo) {
                throw new ApiException('非法请求');
            }
            $verifyCartComplaintModel = new VerifyCartComplaintModel();
            $verifyCartComplaintModel->user_id = $userId;
            $verifyCartComplaintModel->order_id = $orderId;
            $verifyCartComplaintModel->coach_user_id = $orderInfo['coach_id'];
            $verifyCartComplaintModel->img = $img;
            $verifyCartComplaintModel->content = $content;
            $verifyCartComplaintModel->type = 1;
            $verifyCartComplaintModel->save();
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }
}